import React from 'react'
import BaseComponent from 'basecomponent'
import FuncButton from "func-button";
import {Form, Select, Cascader} from 'antd';
import apis from 'apis'
import icons from 'icons'
import './style.scss'
import Button from 'button'
import DropZone from 'react-dropzone'
import {grideType,gradeType} from 'utils/staticType'
import appConfig from 'config'
import {USER_KEY} from 'auth'
import store from 'store'
const FormItem = Form.Item
const typeName = ['FirstTag','SecondTag','ThirdTag'];
class AddMajor extends BaseComponent{
  constructor() {
    super(...arguments);
    this.state= {
      bachelorData:[], //本科
      juniorData:[], //专科
      masterData:[], //硕士
      majorID: -1 , //majorID用于修改
      addMajorDictView:{
        Type: 0,                                //第几级
        Grade: 0,                          //第0级类型->专科:8, 本科:1, 硕士:2
        FirstTag: '',                          //第1级类型
        SecondTag: '',                         //第2级类型名称
        ThirdTag: '',                          //第3级类型名称
        ThirdTagImage: '',                     //第3级类型图片
      },
      addImageTag:'',
      addImagePreview:icons.uploadImg,
      showDrop:false
    }
  }

  componentDidMount(){
    this.getMajorDictList(grideType.bachelor,true)
    this.getMajorDictList(grideType.junior,true)
    this.getMajorDictList(grideType.master,true)
  }

  getMajorDictList(parent,init,targetParent,targetOption){
    const {bachelorData,juniorData,masterData} =this.state
    if(!init){this.majorDListRP.request.abort()}
    this.majorDListRP = apis.majordict.getMajorDictList(parent);
    this.registerRequest(this.majorDListRP.request);
    this.majorDListRP.promise
      .then((res)=>{
        let data = res.Data || [];
        if(init){
          let optionData = data.map(function (item) {
            return {
              value:item.Id,
              label:item.FirstTag,
              origin:item,
              isLeaf: false,
            }
          })
          if(parent === grideType.bachelor){ //本科
            this.setState({bachelorData:optionData})
          }
          if(parent === grideType.junior){ //专科
            this.setState({juniorData:optionData})
          }
          if(parent === grideType.master){ // 硕士
            this.setState({masterData:optionData})
          }
        } else {
          if(targetOption){
            let optionData = data.map(function (item) {
              return {
                value:item.Id.toString(),
                label:item[typeName[item.Type - 1]],
                origin:item,
                isLeaf: item.Type === typeName.length,
              }
            })
            targetOption.children = optionData
            if(targetParent === grideType.bachelor){
              this.setState({bachelorData:[...bachelorData]})
            }
            if(targetParent === grideType.junior){ //专科
              this.setState({juniorData:[...juniorData]})
            }
            if(targetParent === grideType.master){ // 硕士
              this.setState({masterData:[...masterData]})
            }
          }
        }
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }
  handleLoadData(parent,selectedOptions){
    console.log('selectedOptions',selectedOptions)
    const targetOption = selectedOptions[selectedOptions.length - 1];
    this.getMajorDictList(targetOption.value,false,parent,targetOption)
    this.handleOptionChange(selectedOptions)
  }

  onChange(value, selectedOptions){
    this.handleOptionChange(selectedOptions)
  }

  handleOptionChange(selectedOptions){
    if(selectedOptions){
      let option = selectedOptions[selectedOptions.length - 1].origin
      if(option.Type === 3 || option.Type === '3'){
        let url = option.ThirdTagImage ? `${appConfig.apiHost}/File/?pid=${option.ThirdTagImage}&key=${store.get(USER_KEY)}`: icons.uploadImg
        this.setState({showDrop:true , addImagePreview:url})
      }else{
        this.setState({showDrop:false, addImagePreview:icons.uploadImg})
      }
      this.props.form.setFieldsValue({
        Type: option.Type.toString(),
        Grade: option.Grade.toString(),
        FirstTag: option.FirstTag? option.FirstTag:'',
        SecondTag: option.SecondTag? option.SecondTag:'',
        ThirdTag: option.ThirdTag? option.ThirdTag:''
      })
      this.setState({majorID:option.Id})
    }
  }

  handleSaveSubmit(){
    const image = this.state.addImageTag
    this.props.form.validateFields((err, values) => {
      if(!err){
        values.ThirdTagImage = image
        this.addRP && this.addRP.request.abort();
        this.addRP = apis.majordict.addMajorDict(values);
        this.registerRequest(this.addRP.request);
        this.addRP.promise
          .then((res)=>{
            console.log('res', res.Data)
            alert('添加成功')
            let data = res.Data || []
            switch (data.Grade){
              case gradeType.benke:
                this.getMajorDictList(grideType.bachelor,true)
                break
              case gradeType.zhuanke:
                this.getMajorDictList(grideType.junior,true)
                break
              case gradeType.shuoshi:
                this.getMajorDictList(grideType.master,true)
                break
              default:
                break
            }
          })
          .catch((err)=>{
            if(err.code === -12){
              alert('请先添加上一级对象，错误码：-12')
            }else {
              alert(err.msg)
            }
          })
      }
    })
  }
  handleLogoFileSelect(files) {
    let file = files[0];
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort();
      this.uploadLogoRP = apis.file.uploadFile(file);
      this.registerRequest(this.uploadLogoRP.request);
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            addImagePreview: file.preview,
            addImageTag: res.Data || ''
          });
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }
  handleReviseSubmit(){
    const {majorID,addImageTag} = this.state
    this.props.form.validateFields((err, values) => {
      if(!err && majorID > 0){
        values.ThirdTagImage = addImageTag
        console.log(values)
        this.reviseRP && this.reviseRP.request.abort();
        this.reviseRP = apis.majordict.reviseMajorDict(majorID,values);
        this.registerRequest(this.reviseRP.request);
        this.reviseRP.promise
          .then((res)=>{
            alert('修改成功')
            let data = res.Data || []
            switch (data.Grade){
              case gradeType.benke:
                this.getMajorDictList(grideType.bachelor,true)
                break
              case gradeType.zhuanke:
                this.getMajorDictList(grideType.junior,true)
                break
              case gradeType.shuoshi:
                this.getMajorDictList(grideType.master,true)
                break
              default:
                break
            }
          })
          .catch((err)=>{
            if(err.code === -12){
              alert('请先添加上一级对象，错误码：-12')
            }else{
              alert(err.msg)
            }
          })
      }
    })
  }

  render() {
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
    const {bachelorData,juniorData,masterData,addMajorDictView,addImagePreview,showDrop} = this.state;
    return (
        <div className={'class-add-major-page'}>
            <div className={'class-add-major-content'}>
              <FuncButton wrapperName={'class-add-major-FucBtn'}
                          leftText={'保存'}
                          leftTo={()=>{console.log('left click!!')}}
                          rightText={'删除'}
                          rightTo={()=>{console.log('right click!!')}}
              >
              </FuncButton>
              <div className={'add-select-div'}>
                <Cascader className={'level-select '}
                          size={'large'}
                          options={bachelorData}
                          loadData={this.handleLoadData.bind(this,grideType.bachelor)}
                          onChange={this.onChange.bind(this)}
                          placeholder={'本科专业'}
                          notFoundContent={'-'}>
                </Cascader>
                <Cascader className={'batch-select'}
                          size={'large'}
                          options={juniorData}
                          loadData={this.handleLoadData.bind(this,grideType.junior)}
                          onChange={this.onChange.bind(this)}
                          placeholder={'专科专业'}
                          notFoundContent={'-'}>
                </Cascader>
                <Cascader className={'category-select'}
                          size={'large'}
                          options={masterData}
                          loadData={this.handleLoadData.bind(this,grideType.master)}
                          onChange={this.onChange.bind(this)}
                          placeholder={'硕士专业'}
                          notFoundContent={'-'}>
                </Cascader>
              </div>
              <div className={'content-bottom'}>
                <Form className={'add-form'}>
                  <div className={'add-form-div'}>
                    <div className={'form-title-div'}>
                      <span className={'form-title'}>分类详情</span>
                      <Button className={'form-btn'} buttonType={'button'} onClick={this.handleSaveSubmit.bind(this)}>添加</Button>
                      <Button className={'form-btn'} buttonType={'button'} style={{color:'black',backgroundColor:'white'}}
                              onClick={this.handleReviseSubmit.bind(this)}>修改</Button>
                    </div>
                    <div className={'form-content'}>
                      <div className={'grade-title'}>
                        <FormItem>
                          {getFieldDecorator('Type')(
                            <Select className={'class-select'} size={'large'} placeholder={'等级'}
                                    onSelect={(value)=>{
                                      if(value === 3 || value ==='3'){
                                        this.setState({showDrop:true})
                                      }else{
                                        this.setState({showDrop:false})
                                      }
                                    }}
                            >
                              <Option key={1}>{'一级'}</Option>
                              <Option key={2}>{'二级'}</Option>
                              <Option key={3}>{'三级'}</Option>
                            </Select>
                          )}
                        </FormItem>
                        <FormItem>
                          {getFieldDecorator('Grade')(
                            <Select className={'grade-select'} size={'large'} placeholder={'类别'}>
                              <Option key={0}>{'专科'}</Option>
                              <Option key={1}>{'本科'}</Option>
                              <Option key={2}>{'硕士'}</Option>
                            </Select>
                          )}
                        </FormItem>
                      </div>
                      <div className={'content-body'}>
                        <div className={'body-left'}>
                          <div className={'option-wrapper'}>
                            <div className={'option-title'}>一级名称</div>
                            <FormItem>
                              {
                                getFieldDecorator('FirstTag')(
                                  <input className={'option-input'} type={'text'}/>
                                )
                              }
                            </FormItem>
                          </div>
                          <div className={'option-wrapper'}>
                            <div className={'option-title'}>二级名称</div>
                            <FormItem>
                              {
                                getFieldDecorator('SecondTag')(
                                  <input className={'option-input'} type={'text'}/>
                                )
                              }
                            </FormItem>
                          </div>
                          <div className={'option-wrapper'}>
                            <div className={'option-title'}>三级名称</div>
                            <FormItem>
                              {
                                getFieldDecorator('ThirdTag')(
                                  <input className={'option-input'} type={'text'}/>
                                )
                              }
                            </FormItem>
                          </div>
                        </div>
                        <div className={'body-right'}>
                          {
                            showDrop&&
                            <DropZone className={'image-drop-zone'}
                                      onDrop={this.handleLogoFileSelect.bind(this)}
                                      accept={'image/*'}
                                      multiple={false}>
                              <img className={'image-default'} src={addImagePreview}/>
                            </DropZone>
                          }
                        </div>
                      </div>
                    </div>
                  </div>
                </Form>
                {/*<Form className={'revise-form'} onSubmit={this.handleReviseSubmit.bind(this)}>
                  <div className={'revise-form-div'}>
                    <div className={'form-title-div'}>
                      <span className={'form-title'}>修改</span>
                      <Button className={'form-btn'} buttonType={'submit'} onClick={()=>{}}>保存</Button>
                    </div>
                    <div className={'form-content'}>
                      <div className={'grade-title'}>
                        <FormItem>
                          {getFieldDecorator('Type')(
                            <Select className={'class-select'} size={'large'} placeholder={'等级'}>
                              <Option key={1}>{'一级'}</Option>
                              <Option key={2}>{'二级'}</Option>
                              <Option key={3}>{'三级'}</Option>
                            </Select>
                          )}
                        </FormItem>
                        <FormItem>
                          {getFieldDecorator('Grade')(
                            <Select className={'grade-select'} size={'large'} placeholder={'类别'}>
                              <Option key={0}>{'专科'}</Option>
                              <Option key={1}>{'本科'}</Option>
                              <Option key={2}>{'硕士'}</Option>
                            </Select>
                          )}
                        </FormItem>
                      </div>
                      <div className={'content-body'}>
                        <div className={'body-left'}>
                          <div className={'option-wrapper'}>
                            <div className={'option-title'}>一级名称</div>
                            <FormItem>
                              {
                                getFieldDecorator('FirstTag')(
                                  <input className={'option-input'} type={'text'}/>
                                )
                              }
                            </FormItem>
                          </div>
                          <div className={'option-wrapper'}>
                            <div className={'option-title'}>二级名称</div>
                            <FormItem>
                              {
                                getFieldDecorator('SecondTag')(
                                  <input className={'option-input'} type={'text'}/>
                                )
                              }
                            </FormItem>
                          </div>
                          <div className={'option-wrapper'}>
                            <div className={'option-title'}>三级名称</div>
                            <FormItem>
                              {
                                getFieldDecorator('ThirdTag')(
                                  <input className={'option-input'} type={'text'}/>
                                )
                              }
                            </FormItem>
                          </div>
                        </div>
                        <div className={'body-right'}>
                          <DropZone className={'image-drop-zone'}
                                    accept={'image/*'}
                                    multiple={false}>
                            <img className={'image-default'} src={icons.uploadImg}/>
                          </DropZone>
                        </div>
                      </div>
                    </div>
                  </div>
                </Form>*/}
              </div>
            </div>
        </div>
    );
  }
}

module.exports =  Form.create()(AddMajor);
